/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.settlement.web.investorcarcontract;

import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.collect.SetUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.warehourseEnum;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.settlement.entity.investorcarcontract.InvestorCarContract;
import com.jeesite.modules.settlement.entity.investorcarcontract.InvestorCarContractDetail;
import com.jeesite.modules.settlement.service.investorcarcontract.InvestorCarContractService;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;

/**
 * 资方汽车供需合同Controller
 *
 * @author LV
 * @version 2021-03-06
 */
@Controller
@RequestMapping(value = "${adminPath}/settlement/investorCarContract")
public class InvestorCarContractController extends BaseController {

    @Autowired
    private InvestorCarContractService investorCarContractService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private TcarService tcarService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public InvestorCarContract get(String investorCarContractId, boolean isNewRecord) {
        return investorCarContractService.get(investorCarContractId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("settlement:investorCarContract:view")
    @RequestMapping(value = {"list", ""})
    public String list(InvestorCarContract investorCarContract, Model model) {
        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        Supplier supplier = new Supplier();
        supplier.setSupplierType(warehourseEnum.GUONEIZIFANG.getCode());
        model.addAttribute("listSupplier", supplierService.findList(supplier));
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        model.addAttribute("investorCarContract", investorCarContract);
        return "modules/settlement/investorcarcontract/investorCarContractList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("settlement:investorCarContract:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < InvestorCarContract > listData(InvestorCarContract investorCarContract, HttpServletRequest request, HttpServletResponse response) {
        investorCarContract.setPage(new Page <>(request, response));
        Page < InvestorCarContract > page = investorCarContractService.findPage(investorCarContract);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("settlement:investorCarContract:view")
    @RequestMapping(value = "form")
    public String form(InvestorCarContract investorCarContract, Model model) {
        List < ServiceOrder > listServiceOrder = serviceOrderService.findList(new ServiceOrder());
        /*ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(" ");
        serviceOrder.setServiceOrderCode(" ");
        listServiceOrder.add(serviceOrder);*/
        model.addAttribute("listServiceOrder", listServiceOrder);// 服务订单号
        Supplier supplier = new Supplier();
        supplier.setSupplierType(warehourseEnum.GUONEIZIFANG.getCode());
        model.addAttribute("listSupplier", supplierService.findList(supplier));
        List < Tcar > tcarList = tcarService.findList(new Tcar());
        /*Tcar tcar = new Tcar();
        tcar.setCarId(" ");
        tcar.setCarName(" ");
        tcarList.add(tcar);*/
        model.addAttribute("tcarList", tcarList);
        if (investorCarContract.getIsNewRecord()) {
            model.addAttribute("listFrameNumber", ListUtils.newArrayList());
        } else {
            List < ServiceOrderDetail > list = serviceOrderService.getFrameNumberByCondition(investorCarContract.getInvestorId(), investorCarContract.getCompanyId().getCompanyCode());
            for (InvestorCarContractDetail detail : investorCarContract.getInvestorCarContractDetailList()) {
                ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
                serviceOrderDetail.setFrameNumber(detail.getFrameNumber());
                list.add(serviceOrderDetail);
                detail.setCarName(detail.getTcar().getCarName());
                detail.setServiceOrderName(detail.getServiceOrder().getServiceOrderCode());
            }
            model.addAttribute("listFrameNumber", list);
        }
        model.addAttribute("investorCarContract", investorCarContract);
        return "modules/settlement/investorcarcontract/investorCarContractForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("settlement:investorCarContract:view")
    @RequestMapping(value = "detail")
    public String detail(InvestorCarContract investorCarContract, Model model) {
        // 明细合计
        Double calculatePrice = 0D;
        Double price = 0D;
        Double amount = 0D;
        for (InvestorCarContractDetail detail : investorCarContract.getInvestorCarContractDetailList()) {
            calculatePrice = NumberUtils.add(calculatePrice, detail.getCalculatePrice() == null ? 0 : detail.getCalculatePrice());
            price = NumberUtils.add(price, detail.getPrice()== null ? 0 : detail.getPrice());
            amount = NumberUtils.add(amount, detail.getAmount()== null ? 0 : detail.getAmount());
        }
        investorCarContract.setCalculatePrice1(calculatePrice);
        investorCarContract.setPrice1(price);
        investorCarContract.setAmount1(amount);

        model.addAttribute("listServiceOrder", serviceOrderService.findList(new ServiceOrder()));// 服务订单号
        model.addAttribute("listSupplier", supplierService.findList(new Supplier()));
        model.addAttribute("tcarList", tcarService.findList(new Tcar()));
        model.addAttribute("listFrameNumber", serviceOrderService.getFrameNumberByCondition(investorCarContract.getInvestorId(), investorCarContract.getCompanyId().getCompanyCode()));
        model.addAttribute("investorCarContract", investorCarContract);
        return "modules/settlement/investorcarcontract/investorCarContractDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("settlement:investorCarContract:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated InvestorCarContract investorCarContract) {
        List < InvestorCarContractDetail > investorCarContractDetailList = investorCarContract.getInvestorCarContractDetailList();
        HashSet < String > set = SetUtils.newHashSet();
        int code = 0; // 判断是否有重复值
        for (InvestorCarContractDetail detail : investorCarContractDetailList) {
            if (StringUtils.isNotEmpty(detail.getStatus())) {
                set.add(detail.getFrameNumber());
            } else {
                code++;
            }
        }
        if (investorCarContractDetailList.size() != (set.size() + code)) {
            return renderResult(Global.FALSE, text("资方汽车供需合同明细行中存在重复的车架号！"));
        }
        investorCarContractService.save(investorCarContract);
        return renderResult(Global.TRUE, text("保存资方汽车供需合同成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("settlement:investorCarContract:delete")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(InvestorCarContract investorCarContract) {
        investorCarContractService.delete(investorCarContract);
        return renderResult(Global.TRUE, text("删除资方汽车供需合同成功！"));
    }

    /**
     * 列表选择对话框
     */
    @RequiresPermissions("settlement:investorCarContract:view")
    @RequestMapping(value = "investorCarContractSelect")
    public String empUserSelect(InvestorCarContract investorCarContract, String selectData, Model model) {
        String selectDataJson = EncodeUtils.decodeUrl(selectData);
        if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()) {
            model.addAttribute("selectData", selectDataJson);
        }
        model.addAttribute("InvestorCarContract", investorCarContract);
        return "modules/settlement/investorcarcontract/investorCarContractSelect";
    }

}